package com.wsoft.bpm.listener.execute;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wsoft.bpm.entity.ActWorkflowConfigEntity;
import com.wsoft.bpm.service.IActWorkflowConfigService;
import com.wsoft.constant.CommonConstant;
import com.wsoft.core.exception.Asserts;
import com.wsoft.entity.BaseEntity;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.el.ExpressionManager;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 开始流程表达式监听器
 *
 * @Author zhonglj
 * @Date 2024-09-23 15:43
 */
@Component("startProcessAbleListener")
public class StartProcessAbleListener implements ExecutionListener {
    @Resource
    private ProcessEngine processEngine;
    @Resource
    private IActWorkflowConfigService workflowConfigService;

    @Override
    public void notify(DelegateExecution execution) {
        // 获取流程启动表达式
        ActWorkflowConfigEntity startConfig = workflowConfigService.getOne(Wrappers.lambdaQuery(ActWorkflowConfigEntity.class)
                .eq(ActWorkflowConfigEntity::getProcDefId, execution.getProcessDefinitionId())
                .eq(ActWorkflowConfigEntity::getActId, execution.getCurrentActivityId())
                .eq(BaseEntity::getDeleted, CommonConstant.YESNO_NO)
        );

        if (startConfig == null || StrUtil.isBlank(startConfig.getJson())) {
            return;
        }

        Object startCondition = JSONUtil.getByPath(JSONUtil.parseObj(startConfig.getJson()), "startCondition");
        if (startCondition != null) {
            ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration();
            ExpressionManager expressionManager = config.getExpressionManager();
            // 创建表达式
            Expression expression = expressionManager.createExpression(startCondition.toString());
            // 计算表达式的值
            Object value = expression.getValue(execution);
            if (ObjectUtil.notEqual(value, true)) {
                Asserts.fail("[bpm.startProcess.expression]");
            }
        }

    }
}
